<?php

namespace app\index\model;
use think\facade\Db;
use app\common\model\Common;
use app\api\controller\PublicApi;

class CardsTrans extends Common
{
    /**
     * 返回layui的table所需要的格式
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableDataIndex123($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        $user_id = $post['user_id'];
        $where[] = ['user_id', '=', $user_id];
//        $where[] = ['ct.reversal_flag', '<>', 'X'];
        //$where[] = ['ctc.credit_status', '=', 1];
        if(isset($post['tran_status']) && !empty($post['tran_status'])){
            if($post['tran_status'] == 'Authorized'){
                $where[] = ['ct.tran_status', '=', 'Authorized'];
                $where[] = ['ct.reversal_flag', '=', 'N'];
            }else if($post['tran_status'] == 'Reversal'){
                $where[] = ['ct.tran_status', '=', 'Authorized'];
                $where[] = ['ct.reversal_flag', '=', 'Y'];
            }else{
                $where[] = ['ct.tran_status', '=', $post['tran_status']];
            }
        }
        if(isset($post['card_num']) && !empty($post['card_num'])){
            $where[] = ['ct.card_num', 'like', '%'.$post['card_num'].'%'];
        }
        if(isset($post['desc']) && strlen($post['desc'])>0){
            $desc_array = [
                1=>'VERIFY EXPIRATION DATE OR USE NEW CARD',
                2=>'ENHANCED RISK MONITORING DECLINE',
                3=>'VERIFY AMOUNT AND ADJUST LIMIT',
                4=>'VERIFY CVC2 NUMBER ON BACK OF CARD',
                5=>'CALL THE NUMBER ON THE BACK OF THE CARD',
                6=>'CARD IS NOT ACTIVE',
                7=>'FLAG INTERNATIONAL ON CUST F6/05'
            ];
            $where[] = ['ct.desc', '=', $desc_array[$post['desc']]];
        }

        if(isset($post['stime']) && !empty($post['stime'])){
            $start_time = $post['stime'] . " 00:00:00";
            $end_time   = empty($post['ltime'])?"2023-12-31 23:59:59":$post['ltime'];
            $where[] = ['ct.ctime', 'between', "{$start_time},{$end_time}"];
        }
        $card_list = Db::name('cards')
            ->where(['user_id' =>$user_id,'status'=>3])
            ->select()->toArray();
        $del_card_time =[];
        if($card_list){
            foreach ($card_list as $k_card=>$v_card){
                $ctime = Db::name('cards_log')->where(['type'=>4])->value('ctime');
                $del_card_time[$v_card['card_num']] = $ctime;
            }
        }

        $list = Db::name('cards_trans')->alias('ct')
            ->field('ct.*')
            ->order('ct.ctime desc')
            ->where($where)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        if(!empty($list['data'])){
            foreach ($list['data'] as $k=>&$v){
                $tran_status    = $v['tran_status'];
                $bank_type      = $v['bank_type'];
                $card_num       = $v['card_num'];
                $tran_ctime     = strtotime($v['ctime']);
                if($tran_status == 'Credit' && $bank_type != 3){
                    $ctime          = $v['ctime'];
                    $card_num       = $v['card_num'];
                    $card_num_6     = substr($card_num , 0 ,6);
                    if($card_num_6 != '556766'){
                        $amount         = abs($v['amount_auth']);
                        $credit_list    = Db::name('cards_trans_credit')->where([
                            'card_num'  =>$card_num,
                            'ctime'     =>$ctime,
                            'amount'    =>$amount
                        ])->find();
                        if(!empty($credit_list)){
                            $credit_status = $credit_list['credit_status'];
                            if($credit_status != 1){
                                unset($list['data'][$k]);
                            }
                        }else{
                            unset($list['data'][$k]);
                        }
                    }
                }
                if($v['tran_status'] == "Authorized" && $v['reversal_flag'] == 'N'){
                    $v['amount_post'] = $v['amount_auth'];
                }
                if($tran_status == 'Credit'){
                    if(isset($del_card_time[$card_num])){
                        if($tran_ctime - $del_card_time[$card_num] >0){
                            unset($list['data'][$k]);
                        }
                    }
                }
            }
        }
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public function tableDataIndex($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        $user_id = $post['user_id'];
        $where[] = ['user_id', '=', $user_id];
//        $where[] = ['ct.reversal_flag', '<>', 'X'];
        //$where[] = ['ctc.credit_status', '=', 1];
        if(isset($post['tran_status']) && !empty($post['tran_status'])){
            if($post['tran_status'] == 'Authorized'){
                $where[] = ['ct.tran_status', '=', 'Authorized'];
                $where[] = ['ct.reversal_flag', '=', 'N'];
            }else if($post['tran_status'] == 'Reversal'){
                $where[] = ['ct.tran_status', '=', 'Authorized'];
                $where[] = ['ct.reversal_flag', '=', 'Y'];
            }else{
                $where[] = ['ct.tran_status', '=', $post['tran_status']];
            }
        }
        if(isset($post['card_num']) && !empty($post['card_num'])){
            $where[] = ['ct.card_num', 'like', '%'.$post['card_num'].'%'];
        }
        if(isset($post['desc']) && strlen($post['desc'])>0){
            $desc_array = [
                1=>'VERIFY EXPIRATION DATE OR USE NEW CARD',
                2=>'ENHANCED RISK MONITORING DECLINE',
                3=>'VERIFY AMOUNT AND ADJUST LIMIT',
                4=>'VERIFY CVC2 NUMBER ON BACK OF CARD',
                5=>'CALL THE NUMBER ON THE BACK OF THE CARD',
                6=>'CARD IS NOT ACTIVE',
                7=>'FLAG INTERNATIONAL ON CUST F6/05'
            ];
            $where[] = ['ct.desc', '=', $desc_array[$post['desc']]];
        }

        if(isset($post['stime']) && !empty($post['stime'])){
            $start_time = $post['stime'] . " 00:00:00";
            $end_time   = empty($post['ltime'])?"2023-12-31 23:59:59":$post['ltime'];
            $where[] = ['ct.ctime', 'between', "{$start_time},{$end_time}"];
        }
//        $card_list = Db::name('cards')
//            ->where(['user_id' =>$user_id,'status'=>3])
//            ->select()->toArray();
//        $del_card_time =[];
//        if($card_list){
//            foreach ($card_list as $k_card=>$v_card){
//                $ctime = Db::name('cards_log')->where(['type'=>4])->value('ctime');
//                $del_card_time[$v_card['card_num']] = $ctime;
//            }
//        }

        $credit_bank1_list   = Db::name('cards_trans_credit')
            ->where(['user_id'  =>$user_id,'credit_status'=>1])
            ->field('idMatchNumber')
            ->select()->toArray();

        $list = Db::name('cards_trans')->alias('ct')
            ->field('ct.*')
            ->order('ct.ctime desc')
            ->where($where)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        if(!empty($list['data'])){
            foreach ($list['data'] as $k=>&$v){
                $tran_status    = $v['tran_status'];
                $bank_type      = $v['bank_type'];
                $idMatchNumber = $v['idMatchNumber'];
                if($tran_status == 'Credit' && $bank_type != 3){
                    if(!in_array($idMatchNumber,$credit_bank1_list)){
                        unset($list['data'][$k]);
                    }
                }
                if($v['tran_status'] == "Authorized" && $v['reversal_flag'] == 'N'){
                    $v['amount_post'] = $v['amount_auth'];
                }
//                if($tran_status == 'Credit'){
//                    if(isset($del_card_time[$card_num])){
//                        if($tran_ctime - $del_card_time[$card_num] >0){
//                            unset($list['data'][$k]);
//                        }
//                    }
//                }
            }
        }
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }
    public function tableDataInfo($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        $where[] = ['user_id', '=', $post['user_id']];
        $card_num = Db::name('cards')->where(['id'=>$post['card_id']])->value('card_num');
        $where[] = ['card_num', '=', $card_num];
        $where[] = ['reversal_flag', '<>', 'X'];

        $list = Db::name('cards_trans')
            ->field('*')
            ->order('ctime desc')
            ->where($where)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        if(!empty($list['data'])){
            foreach ($list['data'] as $k=>&$v){
                $tran_status    = $v['tran_status'];
                $bank_type      = $v['bank_type'];
                if($tran_status == 'Credit' && $bank_type != 3){
                    $ctime          = $v['ctime'];
                    $card_num       = $v['card_num'];
                    $card_num_6     = substr($card_num , 0 ,6);
                    if($card_num_6 != '556766'){
                        $amount         = abs($v['amount_auth']);
                        $credit_list    = Db::name('cards_trans_credit')->where([
                            'card_num'  =>$card_num,
                            'ctime'     =>$ctime,
                            'amount'    =>$amount
                        ])->find();
                        if(!empty($credit_list)){
                            $credit_status = $credit_list['credit_status'];
                            if($credit_status != 1){
                                unset($list['data'][$k]);
                            }
                        }else{
                            unset($list['data'][$k]);
                        }
                    }
                }
            }
        }
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public function tableDataInfoCode($post)
    {
        $user_id    = $post['user_id'];
        $card_num    = $post['card_num'] ?? '';

        $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => [],
            'count' => 0,
        ];
        $data = [];
        if(!empty($card_num)){
            $card_list  = Db::name('cards')->where(['card_num'=>$card_num , 'user_id'=>$user_id])->find();
            if(!empty($card_list)){
                $card_type = $card_list['card_type'];
                $bank_type = $card_list['bank_type'];
                $card_token= $card_list['card_token'];

                if($bank_type == 3){
                    //搜索消费日志
                    $send_tran_param         = [
                        "user_id"       => 0,
                        "card_num"      => $card_num,
                        "cardGuid"      => $card_token,
                        "action_type"   => "get_tran"
                    ];
                    $send_api = PublicApi::requestApi('Connexpay',$send_tran_param);
                    $return_blog    = $send_api['blog'];
                    $return_list    = $send_api['list'];
                    if($return_blog){
                        if(isset($return_list['transactions'])){
                            $transactions_list = array_reverse($return_list['transactions']);
                            foreach ($transactions_list as $k_tran=>$v_tran){
                                $api_tran_shop      = $v_tran['merchantName'] ?? '';
                                $api_tran_status    = $v_tran['status'];
                                $api_tran_type      = $v_tran['type'];
                                $timestamp          = substr(str_replace('T' , ' ' ,$v_tran['timestamp']) , 0 , 19);
                                //$api_tran_ctime_CDT  = date('Y-m-d H:i:s',strtotime($api_tran_ctime_real . ' -5 hour'));
                                $api_tran_amount    = $v_tran['amount'];

                                if(!empty($api_tran_shop)){
                                    if(substr($api_tran_shop , 0 , 3) == 'PP*'){
                                        if($api_tran_status == "PENDING"){
                                            if($api_tran_type == 'authorization'){
                                                $api_tran_status = 'Authorized';
                                            }
                                        }else if($api_tran_status == "DECLINED"){
                                            if($api_tran_type == 'authorization'){
                                                //正常消费拒绝
                                                $api_tran_status = 'Declined';
                                            }
                                        }else if($api_tran_status == "COMPLETION"){
                                            if($api_tran_type == 'authorization.clearing'){
                                                //正常消费结算
                                                $api_tran_status = 'Posted';
                                            }else if($api_tran_type == 'refund.authorization.clearing'){
                                                //正常退款结算
                                                $api_tran_status = 'Credit';
                                            }
                                        }else if($api_tran_status == "CLEARED"){
                                            if($api_tran_type == 'authorization.reversal'){
                                                //正常撤销
                                                $api_tran_status = 'Reversal';
                                            }else if($api_tran_type == 'authorization.reversal.issuerexpiration') {
                                                $api_tran_status = 'Reversal';
                                            }
                                        }
                                        $data[] =[
                                            'tran_status'   => $api_tran_status,
                                            'reversal_flag' => "N",
                                            'desc'          => $v_tran['description']??'',
                                            'shopping'      => $api_tran_shop,
                                            'amount_auth'   => $api_tran_amount,
                                            'ctime'         => $timestamp,
                                        ];
                                    }
                                }
                            }
                        }
                    }
                }else{
                    $end_time   = date('Y-m-d');
                    $start_time = date("Y-m-d" , strtotime("-1 day"));
                    $data = self::getTimeTran($card_type,$bank_type,$card_num,$start_time,$end_time);
                }
                $result['data']  = array_reverse($data);
                $result['count'] = count($data);
            }
        }

        return $result;
    }

    private static function getTimeTran($card_type,$bank_type,$card_num,$start_time,$end_time)
    {
        $data = [];
        $param      = [
            "user_id"           => 0,
            "action_type"       => "search_trans_test",
            "card_type"         => $card_type,
            "bank_type"         => $bank_type,
            "post_param"  => [
                "card_num"   => $card_num,
                "startDate"  => $start_time,
                "endDate"    => $end_time,
            ]
        ];
        $send_api= PublicApi::requestApi('Comdata',$param);
        $return_blog    = $send_api['blog'];
        $return_list    = $send_api['list'];
        if($return_blog){
            foreach ($return_list as $k=>$v){
                $shopping   = $v['acceptLocation'] ?? '';
                if(!empty($shopping)) {
                    if (substr($shopping, 0, 3) == 'PP*') {
                        $postedDate = $v['postedDate'] ?? '';
                        $utime      = !empty($postedDate) ? $v['postedDate'] . ' ' . $v['postedTime'] : '';
                        $ctime      = $v['transactionDate'] . ' ' . $v['transactionTime'];
                        $reversalFlag = $v['reversalFlag'];
                        $current_status = $v['transactionStatus'];
                        $preAuthAmount  = $v['preAuthAmount'];
                        $postedAmount   = $v['postedAmount'];
                        $correctiveAction = '';
                        if($v['transactionStatus'] == 'Declined'){
                            $correctiveAction = $v['correctiveAction'] ?? '';
                            if(empty($correctiveAction)){
                                $correctiveAction = $v['declineMessage'] ?? '';
                            }
                        }

                        $data[] =[
                            'tran_status'   => $current_status,
                            'reversal_flag' => $reversalFlag,
                            'desc'          => $correctiveAction,
                            'shopping'      => $shopping,
                            'amount_auth'   => $preAuthAmount,
                            'amount_post'   => $postedAmount,
                            'ctime'         => $ctime,
                            'utime'         => $v['transactionStatus'] == 'Declined' ? '' : $utime
                        ];
                    }
                }

            }
        }
        return $data;
    }

    public function getUserPay(){
        $list = Db::name('cards_trans')->alias('ct')
                ->leftJoin('cards c' , 'c.card_num=ct.card_num')
                ->field('c.card_num,ct.ctime,ct.amount_auth,ct.shopping')
                ->order('ct.ctime desc')
                ->where("ct.tran_status='Authorized'")
                ->limit("20")->select()
                ->toArray();
        if($list){
            foreach ($list as $k=>&$v){
                $v['card_num'] = substr($v['card_num'] , -4);
            }
        }
        return $list;
    }

    /**
     * 返回layui的table所需要的格式
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function getList($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where ="ct.type='authorization' and ct.state='PENDING'";
        if(isset($post['desc']) && !empty($post['desc'])){
            $where .= "  and c.card_num like '%{$post['desc']}%' or ct.desc like '%{$post['desc']}%'";
        }

        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode('_' , $post['datetime']);
            $start_time = strtotime($time_list[0] . " 00:00:00") - 8*60*60;
            $end_time   = strtotime($time_list[1] . " 23:59:59") - 8*60*60;
            $where .= " and (ct.ctime between {$start_time} and {$end_time})";
        }

        $list = Db::name('cards_transactions')->alias('ct')
            ->leftJoin('cards c' , 'c.card_token=ct.card_token')
            ->field('c.card_num,ct.desc,ct.ctime,ct.amount')
            ->order('ct.ctime desc')
            ->where($where)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }
}